﻿import { ElementRef, EventEmitter, Injector, Input, Output, Component, OnInit, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as XLSX from 'xlsx';
import { XlsxJsHelper } from '@shared/helpers/XlsxJsHelper';
type AOA = any[][];

@Component({
    selector: 'excel-import',
    template: `
        <span class="input-group-btn">
            <span class="btn btn-file" [ngClass]="'btn-' + btnColor" [ngClass]="{ 'only-link': isLink }">
                <i *ngIf="showIcon" class="fa fa-plus"></i> {{ btnText
                }}<input
                    #fileInput
                    type="file"
                    name="file"
                    single
                    (change)="excelInputUpload($event)"
                    accept=".xlsx,.xls"
                />
            </span>
            <label class="label-file"></label>
        </span>
    `,
    styles: [
        `
            .only-link {
                color: #575962 !important;
                background-color: #fff !important;
                border-color: #fff !important;
            }
        `,
        `
            .only-link:hover:not(:disabled) {
                color: #575962 !important;
                background: #f4f5f8 !important;
                text-decoration: none !important;
            }
        `,
        `
            .btn-file {
                position: relative;
                overflow: hidden;
            }
        `,
        `
            .btn-file input[type='file'] {
                position: absolute;
                top: 0;
                right: 0;
                min-width: 100%;
                min-height: 100%;
                font-size: 100px;
                text-align: right;
                filter: alpha(opacity=0);
                opacity: 0;
                background: red;
                cursor: inherit;
                display: block;
            }
        `,
        `
            .label-file {
                font-size: 18px;
                color: #999;
            }
        `
    ]
})
export class ExcelImportComponent extends AppComponentBase {
    @ViewChild('fileInput') fileInput: ElementRef;
    constructor(injector: Injector, private _element: ElementRef) {
        super(injector);
    }
    @Input() btnColor = '';
    @Input() btnText = '选择文件';
    @Input() showIcon = true;
    @Input() isLink = false;

    @Output() onUpload = new EventEmitter<object>();

    fileName = '';

    excelInputUpload(event) {
        let wb: XLSX.WorkBook; //读取完成的数据
        let rABS = false; //是否将文件读取为二进制字符串

        if (!(event.target.files && event.target.files[0])) {
            return;
        }

        let f = event.target.files[0];

        this.fileName = f.name;

        const reader = new FileReader();

        reader.onload = e => {
            let data = reader.result;
            if (rABS) {
                wb = XLSX.read(btoa(this.fixdata(data)), {
                    //手动转化
                    type: 'base64',
                    cellDates: true
                });
            } else {
                wb = XLSX.read(data, {
                    type: 'binary',
                    cellDates: true
                });
            }

  

            let sheetNames = wb.SheetNames;

            let result = { fileName: this.fileName, fileData: [] };

            sheetNames.forEach(sn => {
                let ws = wb.Sheets[sn];
                let sd = XlsxJsHelper.sheet_to_array(ws);
                let sj = XLSX.utils.sheet_to_json(ws);
                const sheetData = sd.map(el => {
                    let v = el
                        .split('=')
                        .slice(1)
                        .join('=');

                    if (v.indexOf('\'') === 0) {
                        v = v.replace('\'', '');
                    }

                    v = v.replace('\r\n', ' ');

                    return {
                        cell: el.split('=')[0],
                        value: v
                    };
                });

                result.fileData.push({ sheetName: sn, sheetData: sheetData, sheetJson: sj });
            });

            this.onUpload.emit(result);
        };

        if (rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }
    }

    fixdata(data) {
        //文件流转BinaryString
        let o = '',
            l = 0,
            w = 10240;
        for (; l < data.byteLength / w; ++l) {
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        }
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
    }

    clearFileValue() {
        this.fileInput.nativeElement.value = '';
    }
}
